<template>
    <a-modal title="办理任务" :visible="show" width="100%" wrapClassName="full-modal" :confirm-loading="modalLoading"
        @ok="modalOk" @cancel="modalCancel">
        <div>
            <!-- 页签上方的按钮 -->
            <div class="flowBtn">
                <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    保存
                </a-button>
                <a-button type="primary" @click="completeTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    提交
                </a-button>
                <a-button type="primary" @click="returnToClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    退回
                </a-button>
                <a-button type="primary" @click="suspendTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    挂起
                </a-button>
                <a-button type="primary" @click="releaseClaimClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    退签
                </a-button>
                <a-button type="primary" @click="terminateTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    终止
                </a-button>
                <a-button type="primary" @click="approvaledTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    同意
                </a-button>
                <a-button type="primary" @click="rejectTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    拒绝
                </a-button>
                <a-button type="primary" @click="transferTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    转办
                </a-button>
                <a-button type="primary" @click="appendAssigneeTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    追加办理人
                </a-button>
                <a-button type="primary" @click="removeTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    删除任务
                </a-button>
                <a-button type="primary" @click="subTaskClick">
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    加签
                </a-button>
                <!-- <button @click="triggerMethodOnAllPages">触发所有页面的方法</button>
                <button @click="triggerSaveOnAllPages">触发所有页面的方法</button> -->
            </div>
            <a-tabs v-model:activeKey="activeTabKey">
                <a-tab-pane :tab="item.title" :key="item.fullPath" style="height: calc(100vh - 245px);"
                    v-for="(item, index) in tabList">
                    <keep-alive :max="5">
                        <component :is="item.component" :key="item.fullPath" :params="param" :pageParams="item"
                            :ref="(el) => setChildRef(el, item.fullPath)" @vue:mounted="(el) => handleChildMethod(el)"
                            @vue:unmounted="(el) => handleChildMethod(el)" />
                    </keep-alive>
                </a-tab-pane>
            </a-tabs>
        </div>
    </a-modal>

    <!-- 历史任务选择模态框 -->
    <a-modal title="选择退回节点" :visible="historyTaskModalVisible" @ok="confirmReturnTo" @cancel="() => {
        historyTaskModalVisible = false;
        selectedHistoryTask = null;
        returnReason = '';
        reasonRequired = false;
    }" :confirm-loading="historyTaskLoading" width="800px" class="history-task-modal">
        <template #title>
            <div class="modal-title-container">
                <span class="modal-title-text">选择退回节点</span>
                <span class="task-count">(共 {{ historyTaskList.length }} 个节点)</span>
            </div>
        </template>

        <div v-if="historyTaskLoading" class="loading-container">
            <a-spin tip="加载历史节点中..." />
        </div>

        <div v-else class="task-list-container">
            <a-radio-group v-model:value="selectedHistoryTask" class="task-radio-group">
                <div v-for="(task, index) in historyTaskList" :key="task.Id" class="task-item-wrapper">
                    <a-radio :value="task" class="task-radio">
                        <div class="task-card">
                            <div class="task-header">
                                <div class="task-name-section">
                                    <span class="task-index">{{ index + 1 }}.</span>
                                    <span class="task-name">{{ task.Name }}</span>
                                </div>
                                <span class="task-time">{{ formatDateTime(task.CreateTime) }}</span>
                            </div>

                            <div class="task-body">
                                <div class="task-assignee">
                                    <span class="label">处理人：</span>
                                    <span class="value">{{ task.Assigner.Id || task.Assigner?.FullName || '未分配'
                                    }}</span>
                                </div>
                                <div class="task-info">
                                    <span class="label">任务ID：</span>
                                    <span class="value task-id">{{ task.Id }}</span>
                                </div>
                            </div>

                            <div class="task-footer">
                                <span class="task-status">
                                    <CheckCircleOutlined class="status-icon" />
                                    <span>已完成</span>
                                </span>
                            </div>
                        </div>
                    </a-radio>
                </div>
            </a-radio-group>

            <div v-if="historyTaskList.length === 0" class="empty-container">
                <Empty description="暂无历史任务记录" />
            </div>
            <!-- 在任务列表后添加回退原因输入区域 -->

            <div class="reason-section" v-if="historyTaskList.length !== 0">
                <a-form-item label="回退原因" :validate-status="reasonRequired ? 'error' : ''"
                    :help="reasonRequired ? '请输入回退原因' : ''">
                    <a-input v-model:value="returnReason" placeholder="请输入回退原因（必填）" :rows="4" :maxLength="200"
                        show-count class="reason-textarea" @input="handleReasonInput" />
                    <div class="reason-hint">请详细说明退回原因，以便相关人员了解情况并进行处理。</div>
                </a-form-item>
            </div>
        </div>

        <template #footer>
            <div class="modal-footer">
                <a-button @click="() => {
                    historyTaskModalVisible = false;
                    selectedHistoryTask = null;
                    returnReason = '';
                    reasonRequired = false;
                }">
                    取消
                </a-button>
                <a-button type="primary" :loading="historyTaskLoading" @click="confirmReturnTo">
                    确认退回
                </a-button>
            </div>
        </template>
    </a-modal>

    <!-- 其他代码 -->
    <SelectUser :visible="selectUserVisible" :multiple="true" :default-user-ids="defaultUserIds"
        :on-confirm="handleUserConfirm" :on-cancel="handleUserCancel" />
</template>

<script lang="ts" setup>
import { markRaw, defineAsyncComponent, resolveComponent, defineProps, watch, ref, defineEmits, onBeforeUnmount, shallowRef, onMounted } from 'vue';
import { getNodeFormData } from '@/api/workflow/innerform';
import { forEach } from 'lodash';
import { useRoute, useRouter, RouteLocationNormalizedLoaded } from 'vue-router';
import { DownloadOutlined, CheckCircleOutlined } from '@ant-design/icons-vue';
import { resolve } from 'path';
import { completeTask, returnTo, getHistorySingleTaskLists, suspendTask, releaseClaim, approvaledTask, rejectTask, appendAssigneeTask,transferTask ,terminateTask,getHistoryActivityLists,removeTask} from '@/api/flowToDo';
import { notification, message, Empty, Form } from 'ant-design-vue';
import SelectUser from '@/components/sys/selectUser.vue';
import { remove } from 'store';
const { Item: AFormItem } = Form;
interface TabItem {
    fullPath: string;
    name: string;
    title: string;
    component: string | any;
    id: string;
    formId: string;
    businessKey: string;
}
const route = useRoute()
// 弹框路由loading
let modalLoading = ref(false);
// 弹框显隐
let show = ref(false);

// 在现有的ref变量定义后添加
// 历史任务模态框相关状态
const historyTaskModalVisible = ref(false);
const historyTaskList = ref([]);
const selectedHistoryTask = ref(null);
const historyTaskLoading = ref(false);
// 在历史任务模态框相关状态后添加
const returnReason = ref('');
const reasonRequired = ref(false); // 控制是否需要必填验证

const selectUserVisible = ref(false);
const defaultUserIds = ref<string[]>([]); // 默认选中的用户ID
// 处理回退原因输入事件
const handleReasonInput = () => {
    if (reasonRequired.value) {
        reasonRequired.value = false;
    }
}

// 定义接收的属性
const props = defineProps({
    visible: Boolean,
    taskDefinitionKey: String,
    processInstanceId: String,
    businessKey: String,
    taskInfo: Object
});

const param = ref({
    taskDefinitionKey: props.taskDefinitionKey,
    processInstanceId: props.processInstanceId
})

// 定义向外触发的事件
const emits = defineEmits(['update:visible']);
//const modules = import.meta.glob('../views/**/*.{vue,tsx}');
// 监听 visible 属性的变化
watch(() => props.visible, (newValue) => {
    tabList.value = [];
    show.value = newValue;
    if (newValue == true) {
        getNodeFormData({ NodeId: props.taskDefinitionKey }).then(e => {
            let data = e.data.Data;
            data = data.sort((a, b) => a.SortNum - b.SortNum);
            forEach(data, (item) => {
                let viewPath = "/src";
                if (item.FormType == 1) {
                    viewPath = viewPath + item.FormPath;
                } else {
                    viewPath = viewPath + "/views/workbenches/customeForm.vue";
                }
                tabList.value.push({
                    fullPath: item.FormPath,
                    name: item.FormName,
                    title: item.FormName,
                    id: item.Id,
                    formId: item.FormId,
                    businessKey: item.BusinessKey,
                    component: defineAsyncComponent(() =>
                        import(viewPath)
                    )
                })
            })

            param.value = {
                taskDefinitionKey: props.taskDefinitionKey,
                processInstanceId: props.processInstanceId
            }
            // 初始化激活的标签页
            if (tabList.value.length > 0) {
                activeTabKey.value = tabList.value[0].fullPath;
            }
        }).catch(e => {
            console.log(e);
        })
    }
});

const loadModule = async (path: any) => {
    // import 后面是文件路径
    const module = await import(path);
    return module.default;
}

const registerComponent = (componentPath: string) => {
    for (const item in modules) {
        if (item.includes(componentPath)) {
            return defineAsyncComponent(modules[item]);
        }
    }
};
// @desc: 弹框确认事件(回调)
const modalOk = () => {
    emits('ok');
    emits('update:visible', false); // 关闭模态框
}
// @desc: 弹框取消事件(回调)
const modalCancel = () => {
    emits('cancel')
    emits('update:visible', false); // 关闭模态框
    modalLoading.value = false
}

// 当前激活的标签页
const activeTabKey = ref('');

// 动态加载示例
const tabList = ref<TabItem[]>([
    //   {
    //     fullPath: '/dynamic-page',
    //     name: 'DynamicPage',
    //     title: '动态页面',
    //     component: defineAsyncComponent(() => 
    //       import('@/views/workbenches/page2.vue')
    //     )
    //   },
    //   {
    //     fullPath: '/dynamic-page2',
    //     name: 'DynamicPage2',
    //     title: '动态页面2',
    //     component: defineAsyncComponent(() => 
    //       import('@/views/workbenches/page1.vue')
    //     )
    //   }
]);
let activeChildren = {};
const setChildRef = (el, fullPath) => {
    if (el) {
        activeChildren[fullPath] = el;
    } else {
        delete activeChildren[fullPath];
    }
}
// 存储所有子组件的引用
const childComponents = ref([]);

// 处理子组件触发的方法
const handleChildMethod = (child: ComponentPublicInstance | null) => {
    if (!child) return;
    childComponents.value.push(child);
    onBeforeUnmount(() => {
        const index = childComponents.value.indexOf(child);
        if (index > -1) {
            childComponents.value.splice(index, 1);
        }
    });
};


// 触发所有页面的方法
const triggerMethodOnAllPages = () => {
    Object.values(activeChildren).forEach(child => {
        if (child.someMethod) { // 替换为实际方法名
            child.someMethod();
        }
    });
};

const triggerSaveOnAllPages = () => {
    Object.values(activeChildren).forEach(child => {
        if (child.Save) { // 替换为实际方法名
            child.Save();
        }
    });
};

// @desc: 完成任务
const completeTaskClick = () => {
    completeTask({ TaskId: props.taskInfo.Id }).then(e => {
        console.log(e);
        if (e.data.Code == 1 && e.data.Data == true) {
            message.success('完成成功');
            modalCancel();
        } else {
            message.error(e.Message || '完成失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '完成失败');
    })
}

// @desc: 退回任务
const returnToClick = () => {
    historyTaskLoading.value = true;
    getHistorySingleTaskLists({ ProcessInstanceId: props.processInstanceId, ProcessInstanceBusinessKey: props.businessKey }).then(e => {
        historyTaskLoading.value = false;
        if (e.data.Code == 1 && e.data.Data) {
            var historyTaskLists = e.data.Data;
            // 过滤掉当前任务节点
            historyTaskLists = historyTaskLists.filter(item => item.TaskDefinitionKey != props.taskInfo.TaskDefinitionKey);
            historyTaskList.value = historyTaskLists;
            historyTaskModalVisible.value = true;
        } else {
            message.error(e.Message || '获取历史任务失败');
        }
    }).catch(e => {
        historyTaskLoading.value = false;
        console.log(e);
        message.error(e.Message || '获取历史任务失败');
    })
}

// @desc: 确认退回任务
const confirmReturnTo = () => {
    if (!selectedHistoryTask.value) {
        message.warning('请选择要退回的历史任务节点');
        return;
    }
    // 验证回退原因是否填写
    if (!returnReason.value.trim()) {
        message.warning('请输入回退原因');
        reasonRequired.value = true;
        return;
    }
    historyTaskLoading.value = true;
    returnTo({
        TaskId: props.taskInfo.Id,
        ActivityId: selectedHistoryTask.value.TaskDefinitionKey, // 假设历史任务中有TaskId字段
        ReturnReason: returnReason.value.trim() // 添加回退原因字段
    }).then(e => {
        historyTaskLoading.value = false;
        if (e.data.Code == 1 && e.data.Data == true) {
            message.success('退回成功');
            historyTaskModalVisible.value = false;
            returnReason.value = ''; // 清空回退原因
            reasonRequired.value = false;
            modalCancel();
        } else {
            message.error(e.Message || '退回失败');
        }
    }).catch(e => {
        historyTaskLoading.value = false;
        console.log(e);
        message.error(e.Message || '退回失败');
    })
}

//@desc : 挂起任务
const suspendTaskClick = () => {
    suspendTask(props.taskInfo.ProcessInstanceId).then(e => {
        if (e.data.Code == 1) {
            message.success('挂起成功');
            modalCancel();
        } else {
            message.error(e.Message || '挂起失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '挂起失败');
    })

}

// @desc: 退签任务
const releaseClaimClick = () => {
    releaseClaim(props.taskInfo.Id).then(e => {
        if (e.data.Code == 1) {
            message.success('退签成功');
            modalCancel();
        } else {
            message.error(e.Message || '退签失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '退签失败');
    })
}

// @desc: 终止任务
const terminateTaskClick = () => {
    terminateTask({ TaskId: props.taskInfo.Id }).then(e => {
        if (e.data.Code == 1) {
            message.success('终止成功');
            modalCancel();
        } else {
            message.error(e.Message || '终止失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '终止失败');
    })
}

// @desc: 同意
const approvaledTaskClick = () => {
    approvaledTask({ TaskId: props.taskInfo.Id }).then(e => {
        if (e.data.Code == 1) {
            message.success('同意成功');
            modalCancel();
        } else {
            message.error(e.Message || '同意失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '同意失败');
    })
}

// @desc: 拒绝
const rejectTaskClick = () => {
    rejectTask({ TaskId: props.taskInfo.Id }).then(e => {
        if (e.data.Code == 1) {
            message.success('拒绝成功');
            modalCancel();
        } else {
            message.error(e.Message || '拒绝失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '拒绝失败');
    })
}
let operateType = ref('transfer');
// @desc：转办
const transferTaskClick = () => {
    operateType.value = 'transfer';
    defaultUserIds.value = [];
    selectUserVisible.value = true;
    // transferTask({ TaskId: props.taskInfo.Id }).then(e => {
    //     if (e.data.Code == 1) {
    //         message.success('转办成功');
    //         modalCancel();
    //     } else {
    //         message.error(e.Message || '转办失败');
    //     }
    // }).catch(e => {
    //     console.log(e);
    //     message.error(e.Message || '转办失败');
    // })
}

// @desc:追加办理人
const appendAssigneeTaskClick = () => {
    operateType.value = 'append';
     defaultUserIds.value = [];
    selectUserVisible.value = true;
}

// @desc:删除任务
const removeTaskClick = () => {
    removeTask(props.taskInfo.Id).then(e => {
        if (e.data.Code == 1) {
            message.success('删除成功');
            modalCancel();
        } else {
            message.error(e.Message || '删除失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '删除失败');
    })
}

const handleUserConfirm = (userIds: string[]) => {
  console.log('选中的用户ID:', userIds);
  // 处理选中的用户ID
  selectUserVisible.value = false;
  if (operateType.value == 'transfer') {
    transferTask({ TaskId: props.taskInfo.Id, Assignees: userIds }).then(e => {
        if (e.data.Code == 1) {
            message.success('转办成功');
            modalCancel();
        } else {
            message.error(e.Message || '转办失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '转办失败');
    })
  } else if (operateType.value == 'append') {
    appendAssigneeTask({ TaskId: props.taskInfo.Id, Assignees: userIds }).then(e => {
        if (e.data.Code == 1) {
            message.success('追加办理人成功');
            modalCancel();
        } else {
            message.error(e.Message || '追加办理人失败');
        }
    }).catch(e => {
        console.log(e);
        message.error(e.Message || '追加办理人失败');
    })
  }
};

const handleUserCancel = () => {
  selectUserVisible.value = false;
};

// @desc:动态加签
const subTaskClick = () => {

}

// 格式化日期时间
const formatDateTime = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '-');
}
</script>

<style lang="scss">
.reason-section {
    margin-top: 20px;
    padding: 16px;
    background: #fafafa;
    border-radius: 8px;

    .reason-textarea {
        resize: vertical;
        min-height: 100px;
    }

    .reason-hint {
        margin-top: 8px;
        font-size: 12px;
        color: #999;
        line-height: 1.4;
    }
}

.history-task-modal {
    .modal-title-container {
        display: flex;
        align-items: center;

        .modal-title-text {
            font-size: 18px;
            font-weight: 600;
            color: #1890ff;
        }

        .task-count {
            margin-left: 10px;
            font-size: 14px;
            color: #999;
        }
    }

    .loading-container {
        text-align: center;
        padding: 60px 20px;
    }

    .task-list-container {
        max-height: 450px;
        overflow-y: auto;
        padding: 10px 0;

        .task-radio-group {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .task-item-wrapper {
            transition: all 0.3s ease;

            &:hover {
                transform: translateX(4px);
            }
        }

        .task-radio {
            width: 100%;

            .task-card {
                background: #fff;
                border: 2px solid #f0f0f0;
                border-radius: 8px;
                padding: 16px 20px;
                transition: all 0.3s ease;
                cursor: pointer;

                &:hover {
                    border-color: #1890ff;
                    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
                }
            }
        }

        .ant-radio-wrapper-checked {
            .task-card {
                border-color: #1890ff !important;
                background-color: #e6f7ff;
                box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
            }
        }

        .task-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .task-name-section {
                display: flex;
                align-items: center;

                .task-index {
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    width: 24px;
                    height: 24px;
                    background: #1890ff;
                    color: #fff;
                    border-radius: 50%;
                    font-size: 12px;
                    margin-right: 10px;
                }

                .task-name {
                    font-size: 16px;
                    font-weight: 600;
                    color: #333;
                }
            }

            .task-time {
                font-size: 12px;
                color: #999;
                white-space: nowrap;
            }
        }

        .task-body {
            margin-bottom: 12px;

            .task-assignee,
            .task-info {
                display: flex;
                align-items: center;
                margin-bottom: 8px;

                .label {
                    font-size: 13px;
                    color: #666;
                    width: 70px;
                    flex-shrink: 0;
                }

                .value {
                    font-size: 13px;
                    color: #333;
                    word-break: break-all;
                }

                .task-id {
                    font-family: 'Courier New', monospace;
                    background: #f5f5f5;
                    padding: 2px 6px;
                    border-radius: 4px;
                    font-size: 12px;
                }
            }
        }

        .task-footer {

            .task-status {
                display: flex;
                align-items: center;
                font-size: 13px;
                color: #52c41a;

                .status-icon {
                    margin-right: 4px;
                }
            }
        }

        .empty-container {
            text-align: center;
            padding: 80px 20px;
        }
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        padding: 16px 24px;
        border-top: 1px solid #f0f0f0;

        button {
            min-width: 80px;
            margin-left: 10px;
        }
    }
}

.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;
        // 新增样式，让模态框高度为视口高度
        height: 100vh;
    }

    .ant-modal-body {
        flex: 1;
        // 新增样式，让模态框内容区高度自适应
        height: calc(100% - 55px);
        overflow-y: auto;
    }

    // 调整模态框头部和底部样式，让它们也适应新的布局
    .ant-modal-header,
    .ant-modal-footer {
        flex-shrink: 0;
    }

    .flowBtn {
        button {
            margin-left: 10px;
        }
    }

}

/* 覆盖 .ant-tabs-top-content 的 margin-left 样式 */
.ant-tabs-top-content.ant-tabs-content.ant-tabs-content-animated {
    margin-left: 0 !important;
}
</style>